<template>
	<Tabs>
		<TabPane label="分类编辑">
			<Form ref="form" :model="formData" label-position="top" :rules="rules">
				<FormDescItem label="分类名称" prop="name" desc="填写商品分类名称，不可重复且不能为空">
					<Input v-model="formData.name" />
				</FormDescItem>
				<FormDescItem label="上级分类" prop="parent_id" desc="选择商品所属分类，一个商品只能属于一个分类，需要先新增分类">
					<Cascader v-model="formData.parent_id" :data="categoryDatas" change-on-select :load-data="handleLoadCateData"></Cascader>
				</FormDescItem>
				<FormDescItem label="分类图片" desc="上传分类图片，仅顶级分类显示图片，上传后可点击查看大图，建议尺寸为：400px × 400px">
					
				</FormDescItem>
				<!--<FormDescItem label="分类排序" desc="请填写自然数。商品分类将会根据排序进行由小到大排列显示">
					<InputNumber v-model="formData.sort" :precision="0"></InputNumber>
				</FormDescItem>-->
				<FormDescItem label="关联规格" desc="选择分类关联的规格属性，一个分类可以关联多个规格属性">
					<Select>
				        <Option value="beijing">New York</Option>
				        <Option value="shenzhen">Sydney</Option>
				    </Select>
				</FormDescItem>
				<FormDescItem label="关联类型" desc="选择分类关联的类型属性，一个分类只能关联一个类型属性">
					<Select>
				        <Option value="beijing">New York</Option>
				        <Option value="shenzhen">Sydney</Option>
				    </Select>
				</FormDescItem>
				<FormDescItem label="分类状态" desc="请设置商品分类是否启用，如分类关闭启用，则后台以及前台无法查看此分类">
					<RadioGroup v-model="formData.status">
		                <Radio :label="1">开启</Radio>
		                <Radio :label="0">关闭</Radio>
		            </RadioGroup>
				</FormDescItem>
				<!--<FormDescItem label="分类关键词" desc='Keywords项出现在页面头部的标签中，用于记录本页面的关键字，多个关键字请用回车分隔'>
					<InputTags v-model="formData.keywords" :max-str-len="10" />
				</FormDescItem>
				<FormDescItem label="分类描述" desc="Description出现在页面头部的Meta标签中，用于记录本页面的摘要与描述，建议不超过80个字">
					<Input v-model="formData.descript" type="textarea" :rows="5" />
				</FormDescItem>-->
				<FormItem>
					<Button type="primary" :loading="committing" @click="handleSubmit">保存设置并启用</Button>
					<Button @click="handleBack">返回列表</Button>
				</FormItem>
			</Form>
		</TabPane>
	</Tabs>
</template>

<script>
import Util from '@/libs/util.js';
import FormDescItem from '@/components/form/FormDescItem.vue';
import InputTags from '@/components/form/InputTags.vue';
export default {
	components: {
		FormDescItem,
		InputTags
	},
	data() {
		return {
			committing: false,
			categoryDatas: [
				{
                    value: 0,
                    label: '顶级分类'
                }
			],
			pids: [],
			formData: {
				id: '',
				name: '',
				parent_id: [],
				status: 1,
				url: '',
				img: '',
				sort: 100,
				keywords: [],
				descript: ''
			},
			rules: {
				name: [
					{required: true, message: "请填写商品分类名称", trigger: "blur"}
				],
				parent_id: [
					{required: true, type: 'array', message: "请选择上级分类", trigger: "change"}
				]
			}
		}
	},
	computed: {
		reloadCategory() {
			return this.$store.state.app.reloadCategory;
		}
	},
	
	mounted() {
		this.init();
	},
	methods: {
		init() {
			// 添加下级分类
			if(this.$route.query.pids) {
				let ids = this.$route.query.pids.split(',');
				this.pids = ids.map(item => {
					return Number(item);
				})
				this.formData.parent_id = [this.pids[0]];
			}
				
			// 加载一级分类
			Util.ajax.post(this.API['API_GOODS_CATEGORY_LISTS'], {parent_id: 0, is_tree: 0, limit: false, page: false}).then((res) => {
				res.forEach(item => {
					this.categoryDatas.push({
						value: item.id,
                    	label: item.name,
                    	children: [],
                    	loading: false
					})
				})
			}).catch(() => {
				
			})
			
			// 详情
			if(this.$route.query.id) {
				Util.ajax.post(this.API['API_GOODS_CATEGORY_DETAIL'], {id: this.$route.query.id}).then((res) => {
					this.formData.id = res.id;
					this.formData.name = res.name;
					this.formData.parent_id = [res.parent_id];
					this.formData.img = res.img;
					this.formData.url = res.url;
					this.formData.sort = res.sort;
					this.formData.status = res.status;
					this.formData.keywords = res.keywords.split(',');
					this.formData.descript = res.descript;
				}).catch(() => {
					
				})
			}
		},
		handleLoadCateData(item, callback) {
			item.loading = true;
			Util.ajax.post(this.API['API_GOODS_CATEGORY_LISTS'], {parent_id: item.value, is_tree: 0, limit: false, page: false}).then((res) => {
				item.children = res.map(item => {
					return {
						value: item.id,
                    	label: item.name
					}
				})
				item.loading = false;
				if(item.children.length == 0) {
					delete item.children;
					delete item.loading;
				}
				let ids = this.$route.query.pids.split(',');
				ids = ids.map(item => {
					return Number(item);
				})
				// 
				if(this.pids.length > 1) {
					this.formData.parent_id.push(this.pids[1])
				}
				callback();
			}).catch(() => {
				
			})
		},
		handleBack() {
			this.$router.back();
		},
		handleSubmit() {
			if(this.committing) return false;
			this.$refs.form.validate(valid => {
                if(valid) {
                	let form = this.formData;
                	let path = this.API['API_GOODS_CATEGORY_CREATE'];
                	let params = {
                		name: form.name,
						parent_id: form.parent_id[form.parent_id.length - 1],
						status: form.status,
						url: form.url,
						img: form.img,
						sort: form.sort,
						keywords: form.keywords.join(','),
						descript: form.descript
                	}
                	this.committing = true;
                	
                	if(this.formData.id) {
                		// 编辑
                		path = this.API['API_GOODS_CATEGORY_SAVE'];
                		params.id = this.formData.id;
                	}else{
                		// 新增
                		params = {category: params};
                	}
                	Util.ajax.post(path, params).then((res) => {
                		// 设置需要重新获取分类数据
                		this.$store.commit('setReloadCategory', true);
                		this.$Message.success({
                			content: '保存成功',
                			onClose: () => {
                				this.handleBack();
                			}
                		});
                	}).catch(() => {
                		this.committing = false;
                	})
                }
            });
		}
	}
}
</script>